package org.bonorsoft.modules.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.exception.WilliamBootException;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.user.entity.MobileRole;
import org.bonorsoft.modules.user.entity.MobileRoleDept;
import org.bonorsoft.modules.user.entity.MobileRoleMenu;
import org.bonorsoft.modules.user.mapper.MobileRoleDeptMapper;
import org.bonorsoft.modules.user.mapper.MobileRoleMapper;
import org.bonorsoft.modules.user.mapper.MobileRoleMenuMapper;
import org.bonorsoft.modules.user.service.IMobileRoleService;
import org.bonorsoft.modules.user.service.IMobileUserRoleService;
import org.bonorsoft.modules.user.vo.MobileRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

@Service
public class IMobileRoleServiceImpl extends ServiceImpl<MobileRoleMapper, MobileRole> implements IMobileRoleService {
    @Resource
    private MobileRoleMapper roleMapper;
    @Resource
    private MobileRoleMenuMapper roleMenuMapper;
    @Resource
    private MobileRoleDeptMapper roleDeptMapper;
    @Autowired
    private IMobileUserRoleService userRoleService;

    @Override
    public void deleteRole(List<Integer> labelIdList) {
        this.removeByIds(labelIdList);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) throws WilliamBootException {
        idList.forEach(item -> {
            Integer id = Integer.parseInt(item.toString());
            checkRoleAllowed(new MobileRole(id));
            MobileRole role = this.getById(id);
            if (userRoleService.countUserRoleByRoleId(id) > 0) {
                throw new WilliamBootException(String.format("%1$s已分配,不能删除", role.getName()));
            }
        });
        return roleMapper.removeByIds(idList);
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(MobileRole role) {
        if (StringUtils.isNotNull(role.getId()) && role.whetherAdmin()) {
            throw new WilliamBootException("不允许操作超级管理员角色");
        }
//        if ("user".equals(role.getRoleSet()))
//        {
//            throw new BusinessException("普通用户不可进行数据权限分配");
//        }
    }

    /**
     * 根据条件校验角色名称是否唯一
     *
     * @param role      角色信息
     * @param condition 条件
     * @return 结果
     */
    @Override
    public String checkRoleUnique(String field, MobileRole role, String condition) {
        Integer roleId = StringUtils.isNull(role.getId()) ? -1 : role.getId();
        MobileRole info = checkRoleUnique(field, condition);
        if (StringUtils.isNotNull(info) && !info.getId().equals(roleId)) {
            return UserConstants.ROLE_NAME_KEY_NOT_UNIQUE;
        }
        return UserConstants.ROLE_NAME_KEY_UNIQUE;
    }

    /**
     * 根据参数获取角色信息
     *
     * @param field     字段名
     * @param condition 条件
     * @return 角色信息
     */
    private MobileRole checkRoleUnique(String field, String condition) {
        QueryWrapper<MobileRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(field, condition);
        return this.getOne(queryWrapper);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @param req
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(MobileRole role, HttpServletRequest req) {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getId());
        return insertRoleMenu(role, req);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userid 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRoleKeys(String userid) {
        List<MobileRole> perms = roleMapper.selectRolesByUserId(userid);
        Set<String> permsSet = new HashSet<>();
        for (MobileRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询未删除的角色
     *
     * @param roleId
     * @return
     */
    @Override
    public MobileRole selectRoleById(Integer roleId) {
        QueryWrapper<MobileRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("id", roleId);
        return this.getOne(queryWrapper);
    }

    /**
     * 查看某用户的角色
     *
     * @param userid
     * @return
     */
    @Override
    public List<MobileRole> getRolesByUserId(String userid) {
        return roleMapper.getRolesByUserId(userid);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @param req
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(MobileRole role, HttpServletRequest req) {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role, req);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     * @param req
     */
    public int insertRoleMenu(MobileRole role, HttpServletRequest req) {
        String menuIds = req.getParameter("menuIds");
        String[] menuIdLists = menuIds.split(",");
        int rows = 1;
        // 新增用户与角色管理
        List<MobileRoleMenu> list = new ArrayList<MobileRoleMenu>();
        for (String menuId : menuIdLists) {
            MobileRoleMenu rm = new MobileRoleMenu();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     * @param req
     */
    private int insertRoleDept(MobileRole role, HttpServletRequest req) {
        int rows = 1;
        String deptIds = req.getParameter("deptIds");
        if (oConvertUtils.isNotEmpty(deptIds)) {
            String[] deptIdLists = deptIds.split(",");
            // 新增角色与部门（数据权限）管理
            List<MobileRoleDept> list = new ArrayList<MobileRoleDept>();
            for (String deptId : deptIdLists) {
                MobileRoleDept rd = new MobileRoleDept();
                rd.setRoleId(role.getId());
                rd.setDeptId(deptId);
                list.add(rd);
            }
            if (list.size() > 0) {
                rows = roleDeptMapper.batchRoleDept(list);
            }
        }
        return rows;
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<MobileRoleVo> selectRolesByUserId(String userId) {
        List<MobileRole> userRoles = roleMapper.selectRolesByUserId(userId);
        List<MobileRole> roles = this.list();
        List<MobileRoleVo> roleVos = JSONArray.parseArray(JSON.toJSONString(roles), MobileRoleVo.class);
        for (MobileRoleVo role : roleVos) {
            for (MobileRole userRole : userRoles) {
                if (role.getId().equals(userRole.getId())) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roleVos;
    }
}
